const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const model = this.model('admin');
    const data = await model.order(['id DESC']).page(page, size).countSelect();

    return this.success(data);
  }

  async putAction() {
    const values = this.post();
    const id = this.post('id');
    const model = this.model('admin');

    if (id > 0) {
      await model.where({id: id}).update(values);
    } else {
      delete values.id;

      const hasUser = await model.where({username: values.username}).find()
      if(!think.isEmpty(hasUser)){
        return this.fail(400, '用户名被占用');
      }
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()']
      values.password = '123456'
      await model.add({
        password: '123456',
        username: values.username,
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
        name: values.name
      });
    }
    return this.success(values);
  }


  async resetPasswordAction() {
    const id = this.get('id');
    const model = this.model('admin');
    const data = await model.where({id: id}).update({
      password: '123456'
    })
    return this.success(data);
  }

  async changeAction() {
    const values = this.post()
    const admin = await this.model('admin').where({id: this.getLoginUserId()}).find();

    if (values.password !== admin.password) {
      return this.fail(400, '原密码不正确');
    }

    if(values.newpassword1 !== values.newpassword2){
      return this.fail(400, '两次密码输入不一致');
    }

    await this.model('admin').where({id: this.getLoginUserId()}).update({
      password: values.newpassword1
    })
    
    return this.success();
  }


  async destoryAction() {
    const id = this.post('id');
    await this.model('user').where({id: id}).limit(1).delete();
    // TODO 删除图片

    return this.success();
  }
};
